#!/usr/bin/env python
__author__ = 'pal-andreich'


import os
import sys
import optparse
from pwd import getpwnam, getpwuid


def doMount(uid, gid, folderName, mountPath):
    os.system('sudo mount -t vboxsf -o uid={uid},gid={gid} {fName} {mPath}'.format(
        uid=uid,
        gid=gid,
        fName=folderName,
        mPath=mountPath
    ))


def main():
    argParser = optparse.OptionParser(description='mount vbox share folders')
    argParser.add_option('-f', '--folder-name',
                         action='store', dest='folderName', type='string',
                         help='share folder name')
    argParser.add_option('-p', '--mount-path',
                         action='store', dest='mountPath', type='string',
                         help='path to mount')
    argParser.add_option('-u', '--user',
                         action='store', dest='user', type='string',
                         help='share folder name [default: current user]')

    options, args = argParser.parse_args()
    if not options.folderName:
        argParser.error('Folder name is required!')
    if not options.mountPath:
        argParser.error('Mount path is required!')
    if not options.user:
        options.user = (os.getuid(), os.getgid())
    else:
        try:
            uid = int(options.user)
            gid = getpwuid(uid).pw_gid
        except ValueError:
            uid = getpwnam(options.user).pw_uid
            gid = getpwnam(options.user).pw_gid
        options.user = (uid, gid)

    class InputValidator:
        class InvalidInput(Exception): pass
        class Actions:
            create = object()
            mount = object()
            cancel = object()
        @staticmethod
        def validateInput(path):
            if not os.path.exists(path):
                prompt = 'Path: "{0}" doesnt exists\n'.format(path)
                prompt += 'Would you like to create this? '
                confirm = raw_input(prompt)
                if confirm.upper() == 'YES':
                    return InputValidator.Actions.create
                elif confirm.upper() == 'NO':
                    return InputValidator.Actions.cancel
                else:
                    raise InputValidator.InvalidInput('\nYou should type "yes" or "no"')
            else:
                return InputValidator.Actions.mount

    while True:
        try:
            action = InputValidator.validateInput(options.mountPath)
            if action == InputValidator.Actions.create:
                os.makedirs(os.path.join(os.path.curdir, options.mountPath))
                doMount(options.user[0], options.user[1], options.folderName, options.mountPath)
            elif action == InputValidator.Actions.cancel:
                pass
            elif action == InputValidator.Actions.mount:
                doMount(options.user[0], options.user[1], options.folderName, options.mountPath)
            break
        except InputValidator.InvalidInput as ex:
            print ex.message
        except KeyboardInterrupt:
            sys.exit(1)


if __name__ == '__main__':
    if os.name == 'posix':
        main()
    else:
        print 'Should be run on posix system'